import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import eslint from 'vite-plugin-eslint';
import tsconfigPaths from 'vite-tsconfig-paths';
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const {
    BASE_URL,
    VITE_APP_WEB_API_URL,
    VITE_APP_AIGC_API_URL,
    VITE_APP_SOCKET_URL,
  } = loadEnv(mode, process.cwd(), '');

  return {
    base: BASE_URL,
    plugins: [
      react(),
      eslint(),
      tsconfigPaths()
    ],
    server: {
      proxy: {
        '/web': {
          target: `${VITE_APP_WEB_API_URL}/web`,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/web/, ''),
        },
        '/outputs': {
          target: `${VITE_APP_AIGC_API_URL}/outputs`,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/outputs/, ''),
        },
        '/images': {
          target: `${VITE_APP_AIGC_API_URL}/`,
          changeOrigin: true,
        },
        '/upload': {
          target: `${VITE_APP_AIGC_API_URL}/api/upload`,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/upload/, ''),
        },
        // Proxy socket.io to the nodes socketio server
        '/api/ws/socket.io': {
          target: VITE_APP_SOCKET_URL,
          rewrite: (path) =>
            path.replace(/^\/api\/ws\/socket.io/, '/ws/socket.io'),
          ws: true,
        },
        // Proxy openapi schema definiton
        '/openapi.json': {
          target: `${VITE_APP_AIGC_API_URL}/openapi.json`,
          rewrite: (path) => path.replace(/^\/openapi.json/, ''),
          changeOrigin: true,
        },
        // proxy nodes api
        '/api/v1': {
          target: `${VITE_APP_AIGC_API_URL}/api/v1`,
          rewrite: (path) => path.replace(/^\/api\/v1/, ''),
          changeOrigin: true,
        },
      },
    },
  }
})
